//
//  UploadFileHelper.m
//  MIS Cloud
//
//  Created by goldeney on 14-7-22.
//  Copyright (c) 2014年 goldeneye. All rights reserved.
//

#import "UploadFileHelper.h"
#import "FilePathHelper.h"
#import "FileSizeFormatHelper.h"
#import "FileUploadModel.h"
#import "AESCrypt.h"
#import "NSString+HXAddtions.h"
#import "WebGetUserInfoToHttp.h"

@implementation UploadFileHelper
@synthesize uploadinglist = _uploadinglist;
@synthesize delegate = _delegate;

- (id)init
{
    self = [super init];
    if (self) {
        _uploadinglist = [[NSMutableArray alloc] initWithCapacity:0];
    }
    
    return self;
}

- (void)addUploadFileUrl:(NSString*)filePath
{
    if (filePath && ![filePath isEqualToString:@""]) {
        //判断是否重复添加
        for (FileUploadModel *oldModel in _uploadinglist) {
            if ([oldModel.filePath isEqualToString:filePath])
                return;
        }
        
        //查找文件，并开始文件上传
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:filePath traverseLink:YES];
        if (fileAttributes != nil) {
            NSNumber *fileSize = [fileAttributes objectForKey:NSFileSize];
            NSString *fileName = [filePath lastPathComponent];
            
            FileUploadModel *model = [[FileUploadModel alloc] init];
            model.fileName = fileName;
            model.fileSize = [fileSize unsignedLongValue];
            model.filePath = filePath;
            model.sendSize = 0;
            model.sendState = 0;
            [_uploadinglist addObject:model];
            
            [self uploadFileModel:model];
        } else {
            NSLog(@"文件不存在");
        }
    } else {
        NSLog(@"未传入文件路径");
    }
}

- (void)uploadFileModel:(FileUploadModel*)fileModel
{
    //传递用户信息
    NSMutableString *body = [[NSMutableString alloc] initWithCapacity:0];
    NSString *sessionValue = [WebGetUserInfoToHttp getUserInfoToJSON];
    
    NSString *AESsession = [AESCrypt encrypt:sessionValue];
    [body appendString:AESsession];
    
    ConfigurationCodeing *model = [ConfigurationHelper getConfigurationData];
    NSString *newUrl = [NSString stringWithFormat:@"%@%@",model.IpAddress,defaultUpLoadingUrl];
    
    ASIFormDataRequest *request=[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:newUrl]];
    [request setDelegate:self];
    [request setUploadProgressDelegate:self];
    [request setTimeOutSeconds:30.0];//表示30秒请求超时
    [request setPostValue:body forKey:@"session"];
    
    request.userInfo = [NSDictionary dictionaryWithObject:fileModel forKey:@"userInfo"];
    fileModel.request = request;
    
    [request addFile:fileModel.filePath forKey:@"file"];
    [request startAsynchronous];
}

//字典转Json
- (NSString*)dictionaryToJson:(NSDictionary *)dic
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

#pragma mark - ASIHTTPRequestDelegate
- (void)requestFinished:(ASIHTTPRequest *)request
{
    int state = [request responseStatusCode];
    NSString *responseString = [request responseString];
    NSData *responseData = [responseString dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"requestFinished====完成:%d == %@",state,responseString);
    
    NSError *error;
    FileUploadModel *model = [request.userInfo objectForKey:@"userInfo"];
    
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
    if (json && !error) {
        NSUInteger upLoadType = [[json objectForKey:@"upLoadType"] intValue];
        id uploadData = [json objectForKey:@"fileInfo"];
        NSString *uploadResult = [NSString jsonStringWithObject:uploadData];
        
        if (state == 200 && upLoadType == 1) {
            model.sendState = 1;//成功
            model.sendSize = model.fileSize;
            
        } else if (state == 200 && upLoadType == 0) {
            model.sendState = 3;//失败
            model.sendSize = model.fileSize;
            
        } else {
            model.sendState = 2;//其他异常
            model.sendSize = model.fileSize;
        }
        
        [request clearDelegatesAndCancel];
        model.uploadResult = uploadResult;
        
    } else {
        model.sendState = 2;//其他异常
        model.sendSize = model.fileSize;
        model.uploadResult = NULL;
    }
    
    if([self.delegate respondsToSelector:@selector(finishedUpload:)])
        [_delegate finishedUpload:request];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    int state = [request responseStatusCode];
    NSString *response = [request responseString];
    NSLog(@"requestFailed====失败:%d == %@",state,response);
    
    FileUploadModel *model = [request.userInfo objectForKey:@"userInfo"];
    model.sendState = 3;
    [request clearDelegatesAndCancel];
    
    if([self.delegate respondsToSelector:@selector(failedUpload:error:)])
        [_delegate failedUpload:request error:request.error];
}

#pragma mark - ASIProgressDelegate

- (void)request:(ASIHTTPRequest *)request didSendBytes:(long long)bytes
{
    NSString *size = [NSString stringWithFormat:@"%lld",bytes];
    NSString *data = [FileSizeFormatHelper getFileSizeString:size];
    NSLog(@"didSendBytes====%@",data);
    
    FileUploadModel *model = [request.userInfo objectForKey:@"userInfo"];
    model.sendSize += bytes;
    
    if([self.delegate respondsToSelector:@selector(updateCellProgress:sendBytes:)])
        [_delegate updateCellProgress:request sendBytes:bytes];
}

- (void)dealloc
{
    //关闭所有链接
    for (FileUploadModel *model in _uploadinglist) {
        [model.request cancel];
    }
    
    //清理连接
    [_uploadinglist removeAllObjects];
    _delegate = nil;
    _uploadinglist = nil;
}

@end
